<?php
namespace app\web\middleware;

use app\common\util\ErrorCode;
use app\saas\model\trMall;
use think\Response;

// 全局中间件 try catch 捕获异常  检查商城状态
class Check
{
    public function handle($request, \Closure $next)
    {
        /*--- start 跨域用 ---*/
        header('Access-Control-Allow-Origin: *');                                                                 // 允许任意域名发起的跨域请求
        header('Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE');
        header('Access-Control-Allow-Headers: X-Requested-With,X_Requested_With,x-requested-with,content-type');
        /*--- end 跨域用---*/

        $request->mallId = $request->mallId ? $request->mallId : 1; // 后面删除
        if(empty($request->mallId)){
            return Response::create(ErrorCode::code("mall_id_not_exist"), 'json');
        }
        if(!in_array($request->routeInfo()["rule"], ["web/getUpgradeData"])) {
            if (!$mallData = trMall::getCacheData($request->mallId)) {
                db()->getConnection()->close(); // 关闭数据库连接
                return Response::create(ErrorCode::code("customized", "商城不存在"), 'json');
            }
            if ($mallData["isDelete"] != "0") {
                return Response::create(ErrorCode::code("customized", "商城已回收"), 'json');
            }
            if ($mallData["isDisable"] != "0") {
                return Response::create(ErrorCode::code("customized", "商城已禁用"), 'json');
            }
            if (!empty($mallData["expiredTime"]) && $mallData["expiredTime"] <= time()) {
                return Response::create(ErrorCode::code("mall_expired"), 'json');
            }
            if (!empty($request->userLoginData) && $request->mallId != $request->userLoginData["mallId"]) { // 登录了，判断当前用户是不是商城的用户
                db()->getConnection()->close(); // 关闭数据库连接
                return Response::create(ErrorCode::code("customized", "商城mallId错误"), 'json');
            }
        }
        $request->mallData = ["id" => $request->mallId];
        return $next($request);
    }
}
